import Router from "@koa/router";
import jsonwebtoken from "jsonwebtoken";
import config from "../../config"
import { checkCode } from "../../common/utils";
import User from "../../model/User";
import moment from "moment";
import bcrypt, { hash } from "bcrypt";

const router = new Router();

router.prefix("/user");
router.get("/getGoodsList", (ctx) => {
  ctx.body = {
    code: 200,
    data: [
      {
        goodId: 1322522,
        image: "www.baidu.com",
      },
    ],
  };
});

router.post("/login", async (ctx) => {
  // 接收用户的数据
  // 验证图片验证码的时效性, 正确性
  // 验证用户账号密码是否正确
  // 返回token
  // let token = jsonwebtoken.sign({_id: "felix", exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 /* 当前时间加一天 */}, config.JWT_SECRET);
  // 过期时间的另一种写法
  const { body } = ctx.request;
  let sid = body.sid;
  let code = body.code;
  let checkCodeRes = await checkCode(sid, code);
  if(checkCodeRes) {
    // 用户输入的验证码和系统产生的验证码一样, 验证用户账号密码是否正确
    console.log("check OK");
    let checkUserPasswd = false;
    let user = await User.findOne({ username: body.username });
    checkUserPasswd = await bcrypt.compare(body.password, user.password);
    console.log(checkUserPasswd);
    if (checkUserPasswd) {
      // 验证通过, 返回token数据
      let token = jsonwebtoken.sign({_id: "felix"}, config.JWT_SECRET, {expiresIn: "1d"});
      ctx.body = {
        code: 200,
        data: {
          msg: "登陆成功",
          token
        },
      }
    } else {
      // 验证失败, 返回提示
      ctx.body = {
        code: 401,
        msg: "用户名验证错误"
      }
    }
  } else {
    ctx.body = {
      code: 401,
      msg: "图片验证码不正确, 请检查!"
    }
  }
});

router.post("/reg", async (ctx) => {
  // 接收用户的数据
  const { body } = ctx.request;
  // 校验验证码内容
  let sid = body.sid;
  let code = body.code;
  let msg = {};
  let check = true;
  let checkCodeRes = await checkCode(sid, code);

  if (checkCodeRes) {
    let user1 = await User.findOne({username: body.username});
    if (user1 !== null && typeof user1.username !== "undefined") {
      msg.username = ["此邮箱已经注册, 可以邮箱找回密码"]
      check = false;
    }
    let user2 = await User.findOne({name: body.name});
    console.log('user2', user2);
    if (user2 !== null && typeof user2.name !== "undefined") {
      msg.name = ["此昵称已经注册, 请修改"]
      check = false;
    }
    // 写库
    // 给密码加盐
    body.password = await bcrypt.hash(body.password, 5);
    if (check) {
      let user = new User({
        username: body.username,
        password: body.password,
        name: body.name,
        created: moment().format("YYYY-MM-DD HH:mm:ss")
      })
      let result = await user.save();
      ctx.body = {
        code: 200,
        data: result,
        msg: "注册成功",
      }
      return;
    }
  } else {
    msg.vercode = ["验证码已失效, 请重新获取!"]
  }
  ctx.body = {
    code: 500,
    msg
  }
});

export default router;